﻿using System.Xml.Linq;
using System.Xml.Serialization;

namespace TheDealmap.Util
{
    /// <summary>
    /// A utility class that can serialize and deserialize class instances
    /// </summary>
    static class DealSerializer
    {
        /// <summary>
        /// Serializes a runtime class type into a string of xml. 
        /// Removes the xsi:nil namespace values for null elements.
        /// </summary>
        /// <typeparam name="T">A class type that exposes the appropriate serializable interfaces.</typeparam>
        /// <param name="source">The class of the typeparam to be serialized.</param>
        /// <returns></returns>
        public static string Serialize<T>(T source)
        {
            XDocument target = new XDocument();
            XmlSerializer s = new XmlSerializer(typeof(T));
            using (System.Xml.XmlWriter writer = target.CreateWriter())
            {
                s.Serialize(writer, source);
            }

            var xml = target.ToString(SaveOptions.DisableFormatting);
            //By default serializing null values affixes the xsi:nill attribute to
            //an element, easiest to remove it here.
            xml = xml.Replace(" xsi:nil=\"true\"", "");

            return xml;
        }

        /// <summary>
        /// Deserializes an string of xml into an runtime determined class type
        /// </summary>
        /// <typeparam name="T">The class type that is to be deserialized.</typeparam>
        /// <param name="xml">A string containing the xml representation of a class to be deserialized.</param>
        /// <returns></returns>
        public static T DeSerialize<T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
                return default(T);
            XDocument xDoc = XDocument.Parse(xml);
            XmlSerializer s = new XmlSerializer(typeof(T));
            T other = (T)s.Deserialize(xDoc.CreateReader());
            return other;
        }
    }
}
